package com.xauto.pioneer.appuser.activity.common;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.util.PayResult;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 支付工具类
 * Created by Lemon on 10/05/2017.
 */
public class PayUtil {

    /** 支付宝支付回调线程*/
    private Handler handler;
    /** 使用支付的ui界面*/
    private Activity activity;
    /** 支付参数：调起第三方支付控件完整数据*/
    private String payment_order_param;
    public static final int SDK_PAY_FLAG = 10000;
    private String TAG = "PayUtil";
    String paymentCode;
    private LoadingDialog loadingDialog;
    //微信支付
    private  IWXAPI msgApi ;
    public PayUtil(Activity activity, String payment_order_param,String paymentCode) {
        this.activity = activity;
        this.paymentCode = paymentCode;
        this.payment_order_param = payment_order_param;
        if(loadingDialog == null) {
            loadingDialog = new LoadingDialog(activity, "正在加载");
        }
        init();
    }

    private void init() {
        handler = new Handler() {
            @SuppressWarnings("unused")
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信
                        Log.e(TAG, payResult.toString());

                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.showShort(activity, "支付宝支付成功");
                            //支付成功之后给相应界面发送通知
                            EventBus.getDefault().post(Constants.PAY_TYPE_ALIPAY);
                        } else {
                            // 判断resultStatus 为非"9000"则代表可能支付失败
                            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                ToastUtil.showShort(activity, "支付结果确认中");
                            }
                            if (TextUtils.equals(resultStatus, "4000")) {
                                ToastUtil.showShort(activity, "未安装支付宝客户端");
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                ToastUtil.showShort(activity, "支付失败");
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };
        switch (paymentCode){
            case Constants.PAY_TYPE_ALIPAY:
                startAliPay();
                break;
            case Constants.PAY_TYPE_WECHAT:
                startWxPay();
                break;
        }
    }

    /** 调起支付宝控件*/
    private void startAliPay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payment_order_param, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /** 调起微信支付控件*/
    private void startWxPay() {
        msgApi= WXAPIFactory.createWXAPI(activity, Constants.WX_APP_ID);
        msgApi.registerApp(Constants.APP_ID);
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        if(!isWXAppInstalledAndSupported(msgApi)){
            ToastUtil.showShort(activity, "微信客户端未安装，请确认");
        }else{
            try {
                JSONObject obj = new JSONObject(payment_order_param);
                PayReq req = new PayReq();
                req.appId = obj.optString("appid");
                req.partnerId = obj.optString("partnerid");
                req.prepayId = obj.optString("prepayid");
                req.packageValue = "Sign=WXPay";
                req.nonceStr = obj.optString("noncestr");
                req.timeStamp = obj.optString("timestamp");
                req.sign = obj.optString("paySign");
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                msgApi.registerApp(req.appId);
                msgApi.sendReq(req);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    /**判断手机是否安装微信客户端*/
    private boolean isWXAppInstalledAndSupported(IWXAPI api) {
        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            Log.e("TAG", "~~~~~~~~~~~~~~微信客户端未安装，请确认");
        }
        return sIsWXAppInstalledAndSupported;
    }


}
